﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Runtime.Serialization;
using System.Configuration;


namespace SkynetWorker
{
    public class WorkerRole : RoleEntryPoint
    {

        private CloudQueue queueClient;
        private UnityContainer containerService;  
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            //Trace.WriteLine("SkynetWorker entry point called", "Information");
            var business = this.containerService.Resolve<Skynet.BusinessLogic.BusinessComponents.IBCExams>();
            while (true)
            {
                Thread.Sleep(10000);
                Trace.WriteLine("Working", "Information");
                var message = this.queueClient.GetMessage();
                if (message != null)
                {
                    var mem = new System.IO.MemoryStream(message.AsBytes);
                    var dcs = new DataContractSerializer(typeof(Skynet.BusinessEntities.ExamCategory));
                    var category = dcs.ReadObject(mem) as Skynet.BusinessEntities.ExamCategory;
                    business.MaintenanceExamCategories(new List<Skynet.BusinessEntities.ExamCategory>() { category });
                    this.queueClient.DeleteMessage(message);
                }
            }
        }

        public override bool OnStart()
        {            
            ServicePointManager.DefaultConnectionLimit = 12;

            DiagnosticMonitor.Start("DiagnosticsConnectionString");
            
            RoleEnvironment.Changing += RoleEnvironmentChanging;
            Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

            this.queueClient = CreateQueueClient("skynetlibraryqueue");


            containerService = new UnityContainer();
          
            
            var AspectMap = new ExeConfigurationFileMap() { ExeConfigFilename = "./Config/Aspect.config" };
            var AspectSection = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(AspectMap, ConfigurationUserLevel.None).GetSection("unity") as UnityConfigurationSection;
            containerService.LoadConfiguration(AspectSection);

            
            var DataAccessMap = new ExeConfigurationFileMap() { ExeConfigFilename = "./Config/DataAccess.config" };
            var DataAccessSection = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(DataAccessMap, ConfigurationUserLevel.None).GetSection("unity") as UnityConfigurationSection;
            containerService.LoadConfiguration(DataAccessSection);

            
            var BusinessMap = new ExeConfigurationFileMap() { ExeConfigFilename = "./Config/Business.config" };
            var BusinessSection = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(BusinessMap, ConfigurationUserLevel.None).GetSection("unity") as UnityConfigurationSection;
            containerService.LoadConfiguration(BusinessSection);
            
     

            return base.OnStart();
        }
        private CloudQueue CreateQueueClient(string queueName)
        {
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("InfrastructureConnectionString");
            CloudQueueClient queueStorage = storageAccount.CreateCloudQueueClient();
            CloudQueue queue = queueStorage.GetQueueReference(queueName);
            bool created = queue.CreateIfNotExist();
            if (created)
            {

            }
            return queue;
        }
        private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
        {
            // If a configuration setting is changing
            if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
            {
                // Set e.Cancel to true to restart this role instance
                e.Cancel = true;
            }
        }
    }
}
